package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"homework1030/cache"
	"homework1030/model"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var data []model.Video
	redis_key := "video"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": data,
	})
	return
}
func Detail(c *gin.Context) {
	title := c.Query("title")
	var data []model.Video
	redis_key := "video_" + title
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("title like ?", "%"+title+"%").Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": data,
	})
	return
}
func Like(c *gin.Context) {
	id, _ := strconv.Atoi(c.PostForm("id"))
	var video model.Video
	model.DB.Where("id = ?", id).Find(&video)
	data := model.Favorite{
		Title:   video.Title,
		Content: video.Content,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "点赞成功",
	})
	return
}
